package com.zjh.rocketmq.listener;

import com.zjh.rocketmq.annotation.RocketmqTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

@Service
@RocketmqTransactionListener(topic = "topic1", selectorExpression = "111112")
public class ProducerListener implements RocketMQLocalTransactionListener {
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        try {
            System.out.println("producter执行分支事务的msg:" + msg.getPayload() +"object:" + arg);
            //todo 数据库相关逻辑  报错事务回滚 否则事务提交
            int count = 1;
            System.err.println("==================================开始执行事务===============================");
            return count > 0 ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            System.err.println("=====================================事务执行失败============================================");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        try {
            //todo 数据库相关逻辑  报错事务回滚 否则事务提交
            boolean flag = true;
            return flag ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;
        } catch (Exception e) {
            System.err.println("=====================================事务执行失败222222============================================");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
